package com.wl.springsecuritystudy.thread.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class ThreadConfig {



    @Bean(destroyMethod = "shutdown")
    public ThreadPoolTaskExecutor createThreadPoolTaskExecutor(){
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        // 核心线程数,线程池维护线程的最小数量
        threadPoolTaskExecutor.setCorePoolSize(4);
        // 最大线程数
        threadPoolTaskExecutor.setMaxPoolSize(32);
        // 队列最大长度，当核心线程数达到最大时，新任务会放在队列中排队等待执行
        threadPoolTaskExecutor.setQueueCapacity(200);

        threadPoolTaskExecutor.setAllowCoreThreadTimeOut(true);
        // 线程池维护线程所允许的空闲时间,默认60秒
        threadPoolTaskExecutor.setKeepAliveSeconds(60);
        // 是否是守护线程，默认false
        threadPoolTaskExecutor.setDaemon(true);
        /*
         * Reject策略预定义有四种：
         (1)ThreadPoolExecutor.AbortPolicy策略，是默认的策略,处理程序遭到拒绝将抛出运行时 RejectedExecutionException。
         (2)ThreadPoolExecutor.CallerRunsPolicy策略 ,调用者的线程会执行该任务,如果执行器已关闭,则丢弃.
         (3)ThreadPoolExecutor.DiscardPolicy策略，不能执行的任务将被丢弃.
         (4)ThreadPoolExecutor.DiscardOldestPolicy策略，如果执行程序尚未关闭，则位于工作队列头部的任务将被删除，然后重试执行程序（如果再次失败，则重复此过程）.
         */
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());

        threadPoolTaskExecutor.afterPropertiesSet();

        return threadPoolTaskExecutor;
    }


}
